package cn.b.sky.user.controller;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.common.model.TreeInterface;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.service.MenuService;
import cn.b.sky.user.service.RoleService;
import cn.b.sky.user.service.UserService;
import cn.b.sky.user.service.model.*;
import cn.b.sky.user.service.model.condition.RoleCondition;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/role/*")
public class RoleController extends SecurityController {
  @Resource
  RoleService roleService;

  @Resource
  UserService userService;

  @Resource
  MenuService menuService;

  @RequestMapping("roleList")
  public String roleList(Model model, @ModelAttribute("condition") RoleCondition role, String navTabId) {
    role.setSiteCode(SecurityContextUtil.getSiteCode());
    List<Role> roles = roleService.selectRoleList(role);
    int count = roleService.selectRoleCount(role);
    role.setData(roles);
    role.setTotalCount(count);
    model.addAttribute("page", role);
    model.addAttribute(NAVTABID, navTabId);
    return "role/role_list";
  }

  @RequestMapping("validateRoleCode")
  @ResponseBody
  public boolean validateRoleCode(String roleCode, Model model) {
    boolean isValid = true;
    if (!StringUtils.isBlank(roleCode)) {
      Role role = roleService.selectRole(SecurityContextUtil.getSiteCode(), roleCode);
      if (role != null) {
        isValid = false;
      }
    }
    return isValid;
  }

  @RequestMapping("addRole")
  public String addRole(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    List<TreeInterface> menus = roleService.selectMenuByRole(SecurityContextUtil.getSiteCode(), null);
    model.addAttribute("menus", menus);
    return "role/role_add";
  }

  @RequestMapping("editRole")
  public String editRole(Model model, String navTabId, String id) {

    Role role = roleService.selectRole(SecurityContextUtil.getSiteCode(), id);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("role", role);
    List<UserInfo> users = roleService.selectUserByRole(SecurityContextUtil.getSiteCode(), id);
    model.addAttribute("users", users);
    return "role/role_add";
  }
  
  @RequestMapping("authorizeRole")
  public String authorizeRole(Model model, String navTabId, String id) {
    Role role = roleService.selectRole(SecurityContextUtil.getSiteCode(), id);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("role", role);
    List<TreeInterface> menus = roleService.selectMenuByRole(SecurityContextUtil.getSiteCode(), id);
    model.addAttribute("menus", menus);
    return "role/role_authorize";
  }

  @RequestMapping("viewRole")
  public String viewRole(Model model, String navTabId, String id) {

    Role role = roleService.selectRole(SecurityContextUtil.getSiteCode(), id);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("role", role);
    List<TreeInterface> menus = roleService.selectMenuByRole(SecurityContextUtil.getSiteCode(), id);
    List<UserInfo> users = roleService.selectUserByRole(SecurityContextUtil.getSiteCode(), id);
    model.addAttribute("menus", menus);
    model.addAttribute("users", users);
    return "role/role_view";

  }

  @RequestMapping("selectUser")
  public String selectUser(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    List<UserOrganization> users = userService.selectUserTree(SecurityContextUtil.getSiteCode());
    model.addAttribute("treeList", users);
    return "org/user_select";
  }

  @RequestMapping("selectMenu")
  public String selectMenu(Model model, String navTabId) {
    model.addAttribute(NAVTABID, navTabId);
    List<TreeInterface> menus = menuService.selectMenuList(getSiteCode(),false);
    model.addAttribute("treeList", menus);
    return "role/menu_select";
  }
  
  @RequestMapping("saveAuthorizeRole")
  @ResponseBody
  public DWZResult saveAuthorizeRole(Model model, String navTabId, Role role, String menu, HttpServletRequest request) {
    if (role == null) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }
    role.setSiteCode(SecurityContextUtil.getSiteCode());
    // 处理用户权限
    if (!StringUtils.isEmpty(menu)) {
      List<RoleMenu> menuList = new ArrayList<RoleMenu>();
      String[] menus = menu.split(",");
      for (String s : menus) {
        RoleMenu m = new RoleMenu();
        m.setSiteCode(SecurityContextUtil.getSiteCode());
        m.setRoleCode(role.getRoleCode());
        m.setMenuCode(s);
        setCreateInfo(m);
        menuList.add(m);
      }
      role.setMenus(menuList);
    }
    roleService.authorizeRole(role);
    return dialogAjaxDone(
        getImeViewMessageI18n(null, "successfulOperation.M"),
        null, null, null, null);
  }

  @RequestMapping("saveRole")
  @ResponseBody
  public DWZResult saveRole(Model model, String navTabId, String id, Role role, String user, HttpServletRequest request) {
    if (role == null) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }
    // 处理角色信息
    role.setSiteCode(SecurityContextUtil.getSiteCode());

    if (role.getLockFlag() == null) {
      role.setLockFlag(0);
    }
    if (role.getSystemFlag() == null) {
      role.setSystemFlag(0);
    }
//    // 处理用户权限
//    if (!StringUtils.isEmpty(menu)) {
//      List<RoleMenu> menuList = new ArrayList<RoleMenu>();
//      String[] menus = menu.split(",");
//      for (String s : menus) {
//        RoleMenu m = new RoleMenu();
//        m.setSiteCode(SecurityContextUtil.getSiteCode());
//        m.setRoleCode(role.getRoleCode());
//        m.setMenuCode(s);
//        setCreateInfo(m);
//        menuList.add(m);
//      }
//      role.setMenus(menuList);
//    }
    // 处理角色用户
    if (!StringUtils.isEmpty(user)) {
      List<UserRole> userList = new ArrayList<UserRole>();
      String[] users = user.split(",");
      for (String s : users) {
        UserRole u = new UserRole();
        u.setSiteCode(SecurityContextUtil.getSiteCode());
        u.setUserCode(s);
        u.setRoleCode(role.getRoleCode());
        setCreateInfo(u);
        userList.add(u);
      }
      role.setUsers(userList);
    }
    setCreateInfo(role);
    if (StringUtils.isEmpty(id)) {

      roleService.insertRole(role);
      String forwardUrl = getForwardUrl(request) + "/role/roleList?navTabId=" + navTabId;
      return dialogAjaxDone(
          getImeViewMessageI18n(null, "successfulOperation.M"),
          navTabId, null, forwardUrl, null);
    } else {
      roleService.updateRole(role);
      return dialogAjaxDone(
          getImeViewMessageI18n(null, "successfulOperation.M"),
          null, null, null, null);
    }

  }

  @RequestMapping("deleteRole")
  @ResponseBody
  public DWZResult deleteRole(Model model, String navTabId, HttpServletRequest request) {

    String ids = request.getParameter("ids");
    if (StringUtils.isEmpty(ids)) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }
    String[] ress = ids.split(",");
    List<BatchJobReport> reports = new ArrayList<BatchJobReport>(ress.length);
    boolean hasFail = false;
    for (String res : ress) {
      BatchJobReport report = roleService.deleteRole(SecurityContextUtil.getSiteCode(), res);
      reports.add(report);
      if (!report.isSuccess()) {
        hasFail = true;
      }
    }
    if (!hasFail) {
      // 直接返回成功消息
      return navTabAjaxDone(navTabId, null, null, null,
          getImeViewMessageI18n(null, "successfulOperation.M"),
          null);
    } else {
      return batchjobAjaxDone( request, reports);
    }

  }

  @RequestMapping({ "flowNodeRoleLookUp" })
  public String flowNodeRrLookUp(Model model, @ModelAttribute("condition") RoleCondition role) {
    role.setSiteCode(SecurityContextUtil.getSiteCode());
    List<Role> roles = roleService.selectRoleList(role);
    int count = roleService.selectRoleCount(role);
    role.setData(roles);
    role.setTotalCount(count);
    model.addAttribute("page", role);
    return "engine/flownode/flowNodeRoleLookUp";
  }

  @RequestMapping({ "flowNodeRoleSuggest" })
  @ResponseBody
  public Object flowNodeRoleSuggest(@ModelAttribute("condition") RoleCondition role) {
    role.setSiteCode(SecurityContextUtil.getSiteCode());
    return roleService.selectRoleList(role);
  }

}
